<?
ob_start();

/**
* Context class get data from HttpContext class and Config.php file and put all in propeties and methods to make easy access their contents
* @package Context
*/
class Context
{
	protected $_site;
	
	protected $_config = array();
	
	protected $_db = array();
	
	public $data = array();
	
	protected $_parametres = array();
	
	protected $_lang = "pt";
	
	protected $_controller = "";
	
	protected $_module = "";
	
	protected $_action = "";
	
	protected $_debug = false;
	
	protected $_parametresN = array();
	
	protected  $_urlController;
	
	protected $_helper = array();


    /*
     * Controle
     */
    public $control = array();


			
	/**
	 * Singleton designer pattern
	 *
	 * @return Context
	 */
	public static final function getInstance()
	{
		static $instance;
		if (!isset($instance))
		{
			$instance = new Context();
		}
		return $instance;
	}
	
	/**
	* Context construtor. Responsavel por todo HTTP do sistema
	* Process Config.php
	* @access 
	* @return void
	*/
	function Context()
	{	
		$this->_config = Config::getValuesConfig();	
		$this->_db = dbConfig::getValuesConfig();	
		
		$this->renderUrl();
		
		$this->setSession('WEBROOT',$this->webroot() .'webroot/'. $this->getConfig('FOLDER_FILES'). '/');
		$this->setSession('PATHSITE',$this->PathWebRoot() . FileUtil::Slash() . $this->getConfig('FOLDER_FILES'). FileUtil::Slash());
				
		
		//print_r($this->_parametres);exit;
		/*
		$this->
		$this->_debug = $this->ContextValue("config.DEBUG");		

		$this->_site = $this->getParameter("site");
		
		if ($this->_site == "")
		{
			$this->_site = $this->ContextValue("config.SITE");
		}
		
		$this->_lang = $this->getParameter($this->ContextValue("config.PARAMETRELANGUAGE"));
		
		if(!$this->_lang)
		{
			$this->_lang = $this->ContextValue("config.LANGUAGE");			
		}			
		$this->_contentType = $this->ContextValue('type');	
		
		$this->AddPairToConfig("RefererUrl", $_SERVER['HTTP_REFERER']);		
		$this->AddPairToConfig("CurrentUrl", $_SERVER['REQUEST_URI']);
		*/
		//$this->AddPairToConfig("CurrentUrlModule", $this->ContextValue("config.URLMODULE")."?".$_SERVER["QUERY_STRING"]);
		//$this->AddPairToConfig("SELFURL", $_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"]."&");
				
		//$this->AddPairToConfig("USERNAME", $this->authenticatedUser());
		//$this->AddPairToConfig("USERID", $this->authenticatedUserId());
		//$this->AddPairToConfig("ENGINEEXTENSION", "php");	
		//$this->AddPairToConfig("RefererUrl", $_SERVER['HTTP_REFERER']);	
		
	}
	
	function getConfig($value)
	{
		if($this->_config[strtoupper($value)])
		{
			return $this->_config[strtoupper($value)];
		}
		return "";
	}
	
	function getDbConfig($value)
	{
		if($this->_db[strtoupper($value)])
		{
			return $this->_db[strtoupper($value)];
		}
		return "";
	}
	
	private function renderUrl()
	{            		
		$url = $_GET["url"];	
		
		if(!$url)
        {
        	if($this->getConfig("ENABLE_LANGUAGE"))
				$url = $this->_lang . "/" . $this->getConfig("DEFAULT_CONTROLLER"); 
			else
				$url = $this->getConfig("DEFAULT_CONTROLLER");

			$this->redirectUrl($url);
        }
        
		$parametres = explode("/", $url);		
		
		if($this->getConfig("ENABLE_LANGUAGE"))
		{
			$totalParametres = count($parametres);        
	        if(array_key_exists($parametres[0], $this->getConfig("LANGUAGES")))
	        {            
	            $this->_lang = array_shift($parametres);
	        }
	        else
	        {
	            array_shift($parametres);
	        }
		}

        $totalParametres = count($parametres);		
		if(!$totalParametres)
			return;
            
		$module = array_shift($parametres);

		$this->setModule($module);
		
		if(!empty($parametres[0]))
		{
			$action = array_shift($parametres);
			$this->setAction($action);
		}
		else
		{
			$this->setAction($this->getConfig("DEFAULT_ACTION"));
		}	
		$this->renderParametres($parametres);
		
		
	//	DebugUtil::PrintValue($_POST,"line: ".__LINE__ );exit;
		$this->data = $_POST['data'];
	}

	function renderParametres($values)
	{
		$i = 1;
		foreach($values as $key => $value)
		{
			$value = explode(":", $value);
			if(count($value) > 1)
			{
				$this->_parametresN[$i] = $value[1];
				$this->_parametres[strtoupper($value[0])] = $value[1];
			}
			else
			{
				$this->_parametresN[$i] = $value[0];
				$this->_parametres[$i] = $value[0];
			}			
			$i++;
		}
	}
	
	function getRandomNumber($maxValue) 
	{ 
		return rand(0, $maxValue);
	}
	
	function getLanguageId()
	{
		
	}
	
	function getLanguage()
	{
		return $this->_lang;
	}
	
    function getParameteres()
    {
        return $this->_parametresN;
    }

	function getParameter($paramName)
	{		
		if (array_key_exists($paramName, $_POST))
		{
			return $_POST[$paramName];
		}		
		return "";
	}
	
	function getModule()
	{
		return $this->_module;
	}
    
	function setModule($value)
	{
		$this->_module = $value;
	}
	
	function getController()
	{
		return $this->_controller;
	}		
	function setController($value)
	{
		$this->_controller = $value;
	}	
	function getAction()
	{
		return $this->_action;
	}	
	function setAction($value)
	{
		$this->_action = $value;
	}

	function VirtualPathAbsolute($relativePath)
	{
		if ($relativePath{0} == "/")
		{
			return $relativePath;
		}
				
		//PENDENTE
		$result = $_SERVER["SCRIPT_NAME"];
		$iPath = strrpos($result,"/");
		if($iPath !== false)
		{
			$result = substr($result,0,$iPath);
		}
		if($relativePath{0} == "~")
		{
			return $result.substr($relativePath,1);
		}
		else
		{
			return $result."/".$relativePath;
		}
	}

	/**
	* Access the Context collection and returns the value from a key.
	* @access 
	* @return string
	*/
	function ContextValue($key)
	{
		$keyConfig = strtoupper($key);
		if(is_string($key))
		{
			if (array_key_exists($keyConfig, $this->_parametres))
			{
				return $value = $this->_parametres[$keyConfig];			
			}
			else
			{
				return $this->getParameter($keyConfig);
			}
		}
		if(is_numeric($keyConfig) && $key > 0)
		{
			if($this->_parametresN[$keyConfig])
			return $this->_parametresN[$keyConfig];
		}
	}
	
	function addVariavel($name, $value)
	{
		$this->_parametres[$name] = $value;
	}
	function getVariavel()
	{
		return $this->_parametres;
	}
	
	function IsAuthenticated()
	{		
		if(($this->getSession("SESSION_AUTHUSER") != "") && ( $this->getSession("SESSION_AUTHUSERID") != ""))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	function authenticatedUser()
	{
		if ($this->IsAuthenticated())
		{
			return $this->getSession(SESSION_AUTHUSER);
		}
		return "";		
	}
	
	function authenticatedUserId()
	{
		if ($this->IsAuthenticated())
		{
			return $this->getSession(SESSION_AUTHUSERID);
		}
		return "";		
	}
	
	function authenticatedUserName()
	{
		if ($this->IsAuthenticated())
		{			
			return $this->getSession(SESSION_AUTHUSERNAME);
		}	
		return "";		
	}
	
	function authenticatedUserRole()
	{
		if ($this->IsAuthenticated())
		{
			return $this->getSession(SESSION_AUTHUSERROLE);
		}		
		return "";		
	}

	
	function MakeLogin($user, $id, $name, $role)
	{ 
		$this->setSession(SESSION_AUTHUSER, $user); 
		$this->setSession(SESSION_AUTHUSERID, $id); 
		$this->setSession(SESSION_AUTHUSERNAME, $name); 
		$this->setSession(SESSION_AUTHUSERROLE, $role);	
	} 
	
	function MakeLogout() 
	{ 
		session_unset();
	}	
	
	/**
	* Redireciona Url.
	* @param string $url
	* @return void
	*/
	function redirectUrl($url)
	{		
		header("Location:". $this->webroot() .$url); //Habilitar a function obStart
		exit;
	}
	
	
	/**
	* @access 
	* @param string $name
	* @param string $value
	* @return String
	* @desc Add a value in session
	*/
	 function setSession($name, $value) 
	{ 
		$_SESSION[strtoupper($name)] = $value;		
	} 
	
	/**
	* @access 
	* @param string $name
	* @return void
	* @desc Remove a value in this session
	*/
	 function removeSession($name) 
	{ 
		unset($_SESSION[strtoupper($name)]);		
	} 
	
	/**
	* @access 
	* @param string $name
	* @return String
	* @desc Return the a value in this session
	*/
	 function getSession($name) 
	{ 
		return $_SESSION[strtoupper($name)];
	} 	
	
	function SystemRootPath()
	{
		return realpath($_SERVER['DOCUMENT_ROOT'] . $this->webroot());
	}
	
	function webroot()
	{				
		$web = dirname(dirname($_SERVER['PHP_SELF']));
		if($web == '/')
		{
			return '/';
		}
		return $web . '/';
		
	}
	
	function PathWebRoot()
	{
		return realpath($_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']));
	}
	
	function PathSite()
	{
		return realpath($_SERVER['DOCUMENT_ROOT'] . dirname(dirname($_SERVER['PHP_SELF'])));
	}
	function PathView()
	{
		return $this->PathSite() . FileUtil::Slash() . "view";
	}
	
	function PathLayout()
	{
		return $this->PathSite() . FileUtil::Slash() . "webroot" . FileUtil::Slash() . "layout";
	}
	
	function PathComponentes()
	{
		return $this->PathSite() . FileUtil::Slash() . "componentes" . FileUtil::Slash();
	}
	function PathModel()
	{
		return $this->PathSite() . FileUtil::Slash() . "model" . FileUtil::Slash();
	}
	function PathHelper()
	{
		return $this->PathSite() . FileUtil::Slash() . "helpers" . FileUtil::Slash();
	}
	
	
	function getSiteURL()
	{		
		$protocol = ($_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
		$url = $protocol . $_SERVER["HTTP_HOST"] .  $this->webroot();
		if ($url[strlen($url)-1] != '/')
		{
			$url .= "/";
		}
		return $url;
	}
	
	/**
	 * Obtem o caminho do diretorio
	 *
	 * @return string
	 */
	 function getBaseDir()
	{
		$url = dirname($_SERVER["PHP_SELF"]);
		if ($url[strlen($url)-1] != '/')
		{
			$url .= "/";
		}
		return $url;
	}
	
	
	
	function getDirController()
	{		
		return $this->_urlController;
	}
	
	function setDirController($value)
	{		
		$this->_urlController = $value;
	}
	
	
	
	/**
	 * Coleta dados do arquivos 
	 *
	 * @param string $name
	 * @return UploadFile
	 */
	function getUploadedFile($name)
	{
		$file = new UploadFile();
				
			$property = $_FILES[$name];
			$file->error = $property['error'];
			$file->name = $property['name'];
			$file->size = $property['size'];
			$file->tmp_name = $property['tmp_name'];
			$file->type = $property['type'];
			
			if ($file->error == UPLOAD_ERR_OK && strpos($file->type, 'image/') !== false)
			{
				$file->isImage = true;
			}
			
			$infoArquivo = pathinfo(strtolower($property['name']));
			$file->extensao = strtolower($infoArquivo['extension']);
			
			if($file->extensao == "swf")
			{
				$file->isSWF = true;
			}
			$file->ok = true;
		
		return $file;	
	}	
	
	function isSwf($file)
	{
		$infoArquivo = pathinfo(strtolower($file));
		$extensao = strtolower($infoArquivo['extension']);
		
		if($extensao == "swf")
		{
			return true;
		}
		return false;
	}

	public function BlockPath()
	{
		return $this->FrameworkPath() . "blocks" . FileUtil::Slash();
	}
	
	public function addHelper($name)
	{
		$this->_helper[$name] = $name;
	}
    
	public function getHelper()
	{
		return $this->_helper;
	}

    public function setControl($control)
    {
        $this->control[] = $control;
    }
    
    public function getControl()
    {
       return $this->control;
    }


	public function Runat()
	{
		if ($this->ContextValue('runat') == Runat::Client)
		{
			return Runat::Client;
		}
		return Runat::Server;
	}
	
	public function isRunatClient()
	{
		return ($this->Runat() == Runat::Client);
	}
}
?>